package com.jinxin.platform.cdcardpassmgr.task;

import com.alibaba.fastjson.JSONObject;
import com.jinxin.platform.base.common.pojo.JsonResult;
import com.jinxin.platform.cdcardpassmgr.bean.CdcardpassmgrCard;
import com.jinxin.platform.cdcardpassmgr.bean.CdcardpassmgrDevice;
import com.jinxin.platform.cdcardpassmgr.bean.CdcardpassmgrRecord;
import com.jinxin.platform.cdcardpassmgr.rpc.CdcardpassmgrRpc;
import com.jinxin.platform.cdcardpassmgr.service.ICardpassmgrCardService;
import com.jinxin.platform.cdcardpassmgr.service.ICardpassmgrDeviceService;
import com.jinxin.platform.cdcardpassmgr.service.ICardpassmgrRecordService;
import com.jinxin.platform.cdcardpassmgr.service.impl.CardpassmgrCardServiceImpl;
import com.jinxin.platform.cdcardpassmgr.service.impl.CardpassmgrDeviceServiceImpl;
import com.jinxin.platform.cdcardpassmgr.service.impl.CardpassmgrRecordServiceImpl;
import com.jinxin.platform.cdcardpassmgr.utils.DateUtil;
import com.jinxin.platform.cdcardpassmgr.utils.NumConvertUtil;
import com.jinxin.platform.cdcardpassmgr.utils.SpringContextUtils;
import com.jinxin.platform.cdcardpassmgr.utils.Utils;
import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobKey;
import org.springframework.util.StringUtils;

import java.util.HashMap;

/**
 * All rights Reserved, Designed By www.beonelot.com
 *
 * @version: V1.0
 * @Copyright: www.beonelot.com Inc. All rights reserved.
 * @Description：
 * @Date: 2021-07-09
 * @Author: Lingnan
 **/
@Slf4j
public class SchedulerQuartzJob implements Job {
    private final ICardpassmgrDeviceService deviceService =
            (ICardpassmgrDeviceService) SpringContextUtils.getBeanByClass(CardpassmgrDeviceServiceImpl.class);
    private final ICardpassmgrCardService cardService =
            (ICardpassmgrCardService) SpringContextUtils.getBeanByClass(CardpassmgrCardServiceImpl.class);
    private final ICardpassmgrRecordService recordService =
            (ICardpassmgrRecordService) SpringContextUtils.getBeanByClass(CardpassmgrRecordServiceImpl.class);
    private final CdcardpassmgrRpc cdcardpassmgrRpc =
            (CdcardpassmgrRpc) SpringContextUtils.getBeanByClass(CdcardpassmgrRpc.class);


    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        JobKey jobKey = context.getJobDetail().getKey();
        String deviceId = jobKey.getName();
        CdcardpassmgrDevice device = deviceService.getById(deviceId);
        if(device != null){
            Integer intervalSecond = device.getIntervalSecond();
            if (intervalSecond == null || intervalSecond <= 0) {
                return;
            }
            String serialNum = device.getSerialNum();
            String password = device.getPassword();
            String recordCode = device.getRecordCode();
            Integer recordIndex = Integer.parseInt(device.getRecordIndex());
            Integer readCount = Integer.parseInt(device.getReadCount());
            String deviceMac = device.getDeviceMac();
            if(readCount <= 0){
                return;
            }
            JsonResult jsonResult = cdcardpassmgrRpc.readTheRecord(serialNum, password, recordCode, recordIndex, readCount, deviceMac);
            //JsonResult jsonResult = JsonResult.ok("success","{\"r2\":\"00 00 00 01 00 00 00 00 01 20 11 13 16 47 34 03 01 00 00 00 02 00 00 AA AA AA 20 11 13 16 47 34 05 0C 00 00 00 03 00 00 AA AA AA 20 11 13 16 47 34 06 0C 00 00 00 04 00 00 AA AA AA 20 11 13 16 47 34 07 0C 00 00 00 05 00 00 AA AA AA 20 11 13 16 47 34 08 0C 00 00 00 06 00 00 AA FF AA 20 11 13 16 47 45 01 0C 00 00 00 07 00 00 AA FF AA 20 11 13 16 47 45 02 0C 00 00 00 08 00 00 AA FF AA 20 11 13 16 47 45 03 0C 00 00 00 09 00 00 7F FF FF 20 11 13 16 47 46 01 01 00 00 00 0A 00 00 7F FF FF 20 11 13 16 47 46 02 01 00 00 00 0B 00 00 7F FF FF 20 11 13 16 47 46 03 01 00 00 00 0C 00 00 7F FF FF 20 11 13 16 47 46 04 01 00 00 00 0D 00 00 00 00 07 20 11 13 16 47 47 04 0C 00 00 00 0E 00 00 03 FF FF 20 11 13 16 47 47 04 0C 00 00 00 0F FF FF FF FF FF FF FF FF FF FF FF FF FF 00 00 00 10 FF FF FF FF FF FF FF FF FF FF FF FF FF\",\"code\":\"0\",\"r1\":\"00 00 00 10\"}");
            if(jsonResult.getSuccess()){
                // 更新读卡记录上传断点(序号)及读取量
                JsonResult jsonResult2 = cdcardpassmgrRpc.readThePointRecord(serialNum, password, deviceMac);
                if(jsonResult2.getSuccess()){
                    String dataStr2 = jsonResult2.getData().toString();
                    JSONObject jsonObj = JSONObject.parseObject(dataStr2);
                    String jlwhStr = jsonObj.getString("r2");//读卡记录尾号
                    //String scddStr = jsonObj.getString("r3");//读卡记录上传断点(暂时没用)
                    // 记录尾号作为下一次的查询条件(记录序号)
                    int jlwh = NumConvertUtil.hexStringToInt(jlwhStr);
                    log.info("记录尾号是:" + jlwh);
                    if(jlwh > 0){
                        CdcardpassmgrDevice newDevice = new CdcardpassmgrDevice();
                        newDevice.setId(device.getId());
                        newDevice.setRecordIndex(jlwh+"");
                        newDevice.setNoNeedLogin(true);
                        deviceService.saveOrUpdate(newDevice);
                    }

                }
                String dataStr = jsonResult.getData().toString();
                JSONObject jsonObject = JSONObject.parseObject(dataStr);
                String r2Str = jsonObject.getString("r2");
                log.info("通行记录返回的r2: " + r2Str);
                if(!StringUtils.isEmpty(r2Str)){
                    for (int i = 0; i < readCount; i++) {
                        String lineStr = r2Str.substring(50 * i + i, 50 * (i + 1) + i);
                        String index = lineStr.substring(0, 11).replace(" ","");
                        String cardNum = lineStr.substring(12, 26).replace(" ","");
                        if("FFFFFFFFFF".equals(cardNum)){
                            break;
                        }
                        String timeStr = "20"+lineStr.substring(27, 44).replace(" ","");
                        String doorStr = lineStr.substring(45, 47).replace(" ","");
                        String status = lineStr.substring(48, 50).replace(" ","");
                        if(!"01".equals(status)){ // 01合法开门
                            continue;
                        }
                        String id = timeStr + doorStr;
                        CdcardpassmgrRecord record = recordService.selectById(id);
                        if(record == null){
                            String cardNumStr = NumConvertUtil.hexStringToInt(cardNum,8);
                            HashMap param2 = new HashMap();
                            param2.put("cardNum",cardNumStr);
                            CdcardpassmgrCard card = cardService.selectOne(param2);
                            if(card != null){ //只有登记了的卡号才插入数据库
                                record = new CdcardpassmgrRecord();
                                record.setId(id);
                                record.setCardNum(cardNumStr);
                                record.setTypeId(card.getTypeId());
                                record.setType(card.getType());
                                record.setCarNum(card.getCarNum());
                                int direction = Utils.isOdd(Integer.parseInt(doorStr)) ? 1 : 2; // 通行方向1进2出
                                record.setPassTime(DateUtil.timeString2LocalDateTime(timeStr,"yyyyMMddHHmmss"));
                                record.setDirection(direction);
                                record.setProjectId(card.getProjectId());
                                record.setMac(deviceMac);
                                recordService.saveOrUpdate(record,true);
                            }
                        }
                    }
                }
            }
        }

    }
}
